import type { InjectionKey } from 'vue'
import { RouteRecordRaw } from 'vue-router'
import { createStore, useStore as baseUseStore, Store } from 'vuex'
import { getUserInfo } from '@/api/userInfo';
import { getToken, setToken } from '@/utils/auth'

export interface User {
  orgName: string
  gender: number
  userName: string
  orgId: number
  token: string
  roleCode: Array<string>
  roleName: Array<string>
  email: string
  id: string
  level: number
  name: string
  sfwjsr: string
}


const state = {
  user: {} as User,
  orgList: [] as any
}

export type State = typeof state

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol('store')

export const store = createStore<State>({
  state,
  mutations: {
    // 设置用户
    setUser (state, data) {
      state.user = data
      setToken('user', data)
    },
    // 设置组织机构
    setOrgList (state, orgList) {
      state.orgList = orgList
    }
  },
  actions: {
    // 设置用户信息
    async setUserInfo ({ commit }) {
      try {
        const data = await getUserInfo()
        commit('setUser', data.data)
      } catch (e) {}
    },
  },
  getters: {
    // 根据id获取组织机构对象
    getUser: state => {
      return state.user
    }
  }
})

export function useStore () {
  return baseUseStore(key)
}
